package cn.lecosa.spark.mysql

import java.util.concurrent.ConcurrentHashMap
import com.jolbox.bonecp.{ BoneCPConfig, BoneCP }
import java.util.ResourceBundle
import java.util.LinkedList
import java.sql.DriverManager
import java.sql.Connection
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession

/**
 * 数据库连接池工具类
 * 语言：scala
 * 时间：2016-07-09
 */
object JdbcUtil {

  val prop = new java.util.Properties
  prop.setProperty("user", "root")
  prop.setProperty("password", "root")

  //  private val reader = ResourceBundle.getBundle("jdbc")
  private val max_connection = 8 // reader.getString("jeecg.max_connection") //连接池总数
  private val connection_num = 10 // reader.getString("jeecg.connection_num") //产生连接数
  private var current_num = 0 //当前连接池已产生的连接数
  private val pools = new LinkedList[Connection]() //连接池
  private val driver = "com.mysql.jdbc.Driver" // reader.getString("jeecg.driver")
  private val url = "jdbc:mysql://park01:3306/test?useUnicode=true&characterEncoding=UTF-8" // reader.getString("jeecg.url")
  private val username = "root" // reader.getString("jeecg.username")
  private val password = "root" // reader.getString("jeecg.password")

  /**
   * 加载驱动
   */
  private def before() {
    if (current_num > max_connection.toInt && pools.isEmpty()) {
      print("busyness")
      Thread.sleep(2000)
      before()
    } else {
      Class.forName(driver)
    }
  }
  /**
   * 获得连接
   */
  private def initConn(): Connection = {
    val conn = DriverManager.getConnection(url, username, password)
    conn
  }
  /**
   * 初始化连接池
   */
  private def initConnectionPool(): LinkedList[Connection] = {
    AnyRef.synchronized({
      if (pools.isEmpty()) {
        before()
        for (i <- 1 to connection_num.toInt) {
          pools.push(initConn())
          current_num += 1
        }
      }
      pools
    })
  }
  /**
   * 获得连接
   */
  def getConn(): Connection = {
    initConnectionPool()
    pools.poll()
  }

  def getProp(): java.util.Properties = {
      this.prop
  }
  /**
   * 释放连接
   */
  def releaseCon(con: Connection) {
    pools.push(con)
  }

  /** Lazily instantiated singleton instance of SparkSession */
  object SparkSessionSingleton {

    @transient private var instance: SparkSession = _

    def getInstance(sparkConf: SparkConf): SparkSession = {
      if (instance == null) {
        instance = SparkSession
          .builder
          .config(sparkConf)
          .getOrCreate()
      }
      instance
    }
  }
}